package com.front.managementfront.driver.service.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.front.managementfront.driver.entity.*;
import com.front.managementfront.driver.mapper.*;
import com.front.managementfront.driver.service.IHktsDriverService;
import com.front.managementfront.driver.service.IHktsRealNameAuthenticationService;
import com.front.managementfront.utils.PhotoUtils;
import com.hkts.management.common.vo.DriverListInfoVo;
import com.front.managementfront.driver.vo.RealNameVo;
import com.front.managementfront.fegin.IUserAppServiceClient;
import com.front.managementfront.fegin.OrderAppServiceClient;
import com.front.managementfront.utils.CustomPageUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hkts.management.common.utils.CustomPage;
import com.hkts.management.common.utils.Result;
import com.hkts.management.common.utils.ResultUtil;
import com.hkts.management.common.vo.UserBasicInfoVo;
import com.hkts.management.common.vo.UserOderNumVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yck
 * @since 2021-05-09
 */
@Service
@Transactional
public class HktsRealNameAuthenticationServiceImpl extends ServiceImpl<HktsRealNameAuthenticationMapper, HktsRealNameAuthentication> implements IHktsRealNameAuthenticationService {
    @Autowired
    private OrderAppServiceClient orderAppServiceClient;

    @Autowired
    private HktsRealNameAuthenticationMapper hktsRealNameAuthenticationMapper;

    @Autowired
    private IHktsDriverService driverMapper;

    @Autowired
    private IUserAppServiceClient iUserAppServiceClient;

    @Autowired
    private HktsDriverDetailMapper hktsDriverDetailMapper;
    @Autowired
    private CertificateImgMapper certificateImgMapper;
    @Autowired
    private CarInfoMapper carInfoMapper;


    @Override
    public IPage<HktsRealNameAuthentication> selectPage(Page<HktsRealNameAuthentication> page, HktsRealNameAuthentication hktsRealNameAuthentication) {
        QueryWrapper<HktsRealNameAuthentication> query = Wrappers.query();
        QueryWrapper<HktsRealNameAuthentication> entityWrapper = getEntityWrapper(query, hktsRealNameAuthentication);
        return hktsRealNameAuthenticationMapper.selectPage(page, entityWrapper);
    }


    @Override
    public List<HktsRealNameAuthentication> selectList(HktsRealNameAuthentication hktsRealNameAuthentication) {
        QueryWrapper<HktsRealNameAuthentication> query = Wrappers.query();
        QueryWrapper<HktsRealNameAuthentication> entityWrapper = getEntityWrapper(query, hktsRealNameAuthentication);
        return hktsRealNameAuthenticationMapper.selectList(entityWrapper);
    }

    /**
     * 根据用户id查询
     */
    @Override
    public RealNameVo getByUserId(String userId) {
        RealNameVo vo = hktsRealNameAuthenticationMapper.selectOneByUserId(userId);
        if (StringUtils.isNotBlank(vo.getApprovalUser())&&!vo.getApprovalUser().equals("admin")) {
            Result<UserBasicInfoVo> userBasicInfoVoByuserId = iUserAppServiceClient.getUserBasicInfoVoByuserId(vo.getApprovalUser());
            vo.setApprovalUser(userBasicInfoVoByuserId.getResult().getNickName());
        }
        //查询 用户身份证 照片信息
        QueryWrapper<CertificateImg> queryCertificateImg = Wrappers.query();
        queryCertificateImg.lambda().eq(CertificateImg::getUserId,userId);
        queryCertificateImg.lambda().eq(CertificateImg::getDelFlag,0);
        queryCertificateImg.lambda().eq(CertificateImg::getCarId,"0");
        List<CertificateImg> certificateImgs = certificateImgMapper.selectList(queryCertificateImg);
        for(int i=0;i<certificateImgs.size();i++){
            certificateImgs.get(i).setCardPath(PhotoUtils.handlerPtotoUrlPrefix(certificateImgs.get(i).getCardPath()));
            if(vo.getApproval().equals("2")){
                certificateImgs.get(i).setCheckStatus(1);
            }
        }
        Map<String, CertificateImg> collect1 = certificateImgs.stream().collect(Collectors.toMap(CertificateImg::getCertificateType, Function.identity()));
        vo.getPhotoMap().putAll(collect1);
        if(!vo.getApproval().equals("2")){
            QueryWrapper<CarInfo> queryCarInfo = Wrappers.query();
            queryCarInfo.lambda().eq(CarInfo::getDelFlag,0);
            queryCarInfo.lambda().eq(CarInfo::getUserId,userId);
            queryCarInfo.lambda().ne(CarInfo::getApprovalStatus,0);
            List<CarInfo> carInfos = carInfoMapper.selectList(queryCarInfo);

            if(carInfos.size()>0){
                QueryWrapper<CertificateImg> queryCertificateImgs = Wrappers.query();
                queryCertificateImgs.lambda().eq(CertificateImg::getUserId,userId);
                queryCertificateImgs.lambda().eq(CertificateImg::getCarId,carInfos.get(0).getId());
                queryCertificateImgs.lambda().eq(CertificateImg::getDelFlag,"0");
                List<CertificateImg> certificateImgs1 = certificateImgMapper.selectList(queryCertificateImgs);
                for(int i=0;i<certificateImgs1.size();i++){
                    certificateImgs1.get(i).setCardPath(PhotoUtils.handlerPtotoUrlPrefix(certificateImgs1.get(i).getCardPath()));
                }
                Map<String, CertificateImg> imgMap = certificateImgs1.stream().collect(Collectors.toMap(CertificateImg::getCertificateType, Function.identity()));
                vo.getPhotoMap().putAll(imgMap);
            }
        }
        return vo;
    }

    /**
     * 公共查询条件
     *
     * @param entityWrapper
     * @return
     */
    public QueryWrapper<HktsRealNameAuthentication> getEntityWrapper(QueryWrapper<HktsRealNameAuthentication> entityWrapper, HktsRealNameAuthentication hktsRealNameAuthentication) {
        //条件拼接
        if (StringUtils.isNotBlank(hktsRealNameAuthentication.getCreateBy())) {
            entityWrapper.like(HktsRealNameAuthentication.CREATE_BY, hktsRealNameAuthentication.getCreateBy());
        }
                /*if(StringUtils.isNotBlank(hktsRealNameAuthentication.getCreateTime())){
                entityWrapper.like(HktsRealNameAuthentication.CREATE_TIME,hktsRealNameAuthentication.getCreateTime());
                }
                if(StringUtils.isNotBlank(hktsRealNameAuthentication.getDelFlag())){
                entityWrapper.like(HktsRealNameAuthentication.DEL_FLAG,hktsRealNameAuthentication.getDelFlag());
                }*/
        if (StringUtils.isNotBlank(hktsRealNameAuthentication.getUpdateBy())) {
            entityWrapper.like(HktsRealNameAuthentication.UPDATE_BY, hktsRealNameAuthentication.getUpdateBy());
        }
             /*   if(StringUtils.isNotBlank(hktsRealNameAuthentication.getUpdateTime())){
                entityWrapper.like(HktsRealNameAuthentication.UPDATE_TIME,hktsRealNameAuthentication.getUpdateTime());
                }*/
        if (StringUtils.isNotBlank(hktsRealNameAuthentication.getBackIdCardPath())) {
            entityWrapper.like(HktsRealNameAuthentication.BACK_ID_CARD_PATH, hktsRealNameAuthentication.getBackIdCardPath());
        }
        if (StringUtils.isNotBlank(hktsRealNameAuthentication.getCarCode())) {
            entityWrapper.like(HktsRealNameAuthentication.CAR_CODE, hktsRealNameAuthentication.getCarCode());
        }
        if (StringUtils.isNotBlank(hktsRealNameAuthentication.getCopilotPath())) {
            entityWrapper.like(HktsRealNameAuthentication.COPILOT_PATH, hktsRealNameAuthentication.getCopilotPath());
        }
        if (StringUtils.isNotBlank(hktsRealNameAuthentication.getDriverLicenseHomePath())) {
            entityWrapper.like(HktsRealNameAuthentication.DRIVER_LICENSE_HOME_PATH, hktsRealNameAuthentication.getDriverLicenseHomePath());
        }
        if (StringUtils.isNotBlank(hktsRealNameAuthentication.getDriverLicenseSubPath())) {
            entityWrapper.like(HktsRealNameAuthentication.DRIVER_LICENSE_SUB_PATH, hktsRealNameAuthentication.getDriverLicenseSubPath());
        }
        if (StringUtils.isNotBlank(hktsRealNameAuthentication.getDriverName())) {
            entityWrapper.like(HktsRealNameAuthentication.DRIVER_NAME, hktsRealNameAuthentication.getDriverName());
        }
        if (StringUtils.isNotBlank(hktsRealNameAuthentication.getDrivingLicensePath())) {
            entityWrapper.like(HktsRealNameAuthentication.DRIVING_LICENSE_PATH, hktsRealNameAuthentication.getDrivingLicensePath());
        }
        if (StringUtils.isNotBlank(hktsRealNameAuthentication.getEhicleType())) {
            entityWrapper.like(HktsRealNameAuthentication.EHICLE_TYPE, hktsRealNameAuthentication.getEhicleType());
        }
        if (StringUtils.isNotBlank(hktsRealNameAuthentication.getIdCardPath())) {
            entityWrapper.like(HktsRealNameAuthentication.ID_CARDPATH, hktsRealNameAuthentication.getIdCardPath());
        }
        if (StringUtils.isNotBlank(hktsRealNameAuthentication.getIdentity())) {
            entityWrapper.like(HktsRealNameAuthentication.IDENTITY, hktsRealNameAuthentication.getIdentity());
        }
        if (StringUtils.isNotBlank(hktsRealNameAuthentication.getPeopleCarsPath())) {
            entityWrapper.like(HktsRealNameAuthentication.PEOPLE_CARS_PATH, hktsRealNameAuthentication.getPeopleCarsPath());
        }
        if (StringUtils.isNotBlank(hktsRealNameAuthentication.getUserId())) {
            entityWrapper.like(HktsRealNameAuthentication.USER_ID, hktsRealNameAuthentication.getUserId());
        }
        if (StringUtils.isNotBlank(hktsRealNameAuthentication.getVehicleLength())) {
            entityWrapper.like(HktsRealNameAuthentication.VEHICLE_LENGTH, hktsRealNameAuthentication.getVehicleLength());
        }
        return entityWrapper;
    }

    @Override
    public CustomPage<DriverListInfoVo> getDriverInfoPage(IPage<DriverListInfoVo> page, DriverListInfoVo vo) {
        if(vo.getCarApprovalStatus()!=null){
            QueryWrapper<CarInfo> queryWrapper=new QueryWrapper<CarInfo>();
            queryWrapper.lambda().eq(CarInfo::getApprovalStatus,vo.getCarApprovalStatus());
            queryWrapper.lambda().eq(CarInfo::getDelFlag,0);
            List<CarInfo> carInfos = carInfoMapper.selectList(queryWrapper);
            if(carInfos.size()==0){
                CustomPage<DriverListInfoVo> customPage=new CustomPage();
                customPage.setTotalRows((long)0);
                customPage.setTotalPages((long)0);
                customPage.setPageNumber(page.getCurrent());
                customPage.setPageSize(page.getSize());
                return customPage;
            }
            List<String> collect1 = carInfos.stream().map(CarInfo::getUserId).distinct().collect(Collectors.toList());
            vo.setDriverIds(collect1);
        }
        PageHelper.startPage((int) page.getCurrent(), (int) page.getSize());

        List<DriverListInfoVo> driverInfoPage = hktsRealNameAuthenticationMapper.getDriverInfoPage(vo);
        List<String> list = driverInfoPage.stream().map(DriverListInfoVo::getId).collect(Collectors.toList());
        System.out.println(list.toString());
        //订单数目和好评率
        if(list.size()>0){
            QueryWrapper<HktsDriverDetail> query = new QueryWrapper<HktsDriverDetail>();
            query.lambda().in(HktsDriverDetail::getDriverId, list);
            List<HktsDriverDetail> hktsDriverDetails = hktsDriverDetailMapper.selectList(query);
            Map<String, Integer> collect = hktsDriverDetails.stream().collect(Collectors.toMap(HktsDriverDetail::getDriverId, HktsDriverDetail::getTradeCount));
            Map<String, BigDecimal> collect1 = hktsDriverDetails.stream().collect(Collectors.toMap(HktsDriverDetail::getDriverId, HktsDriverDetail::getApplauseRate));
            NumberFormat format=NumberFormat.getPercentInstance();
            for(int i=0;i<driverInfoPage.size();i++){
                driverInfoPage.get(i).setFavorableRate(collect1.get(driverInfoPage.get(i).getId())==null?"":format.format(collect1.get(driverInfoPage.get(i).getId()).floatValue()));
                driverInfoPage.get((i)).setOrderNum(collect.get(driverInfoPage.get(i).getId())==null?0:collect.get(driverInfoPage.get(i).getId()));
            }
        }
        PageInfo pageInfo = new PageInfo<>(driverInfoPage);
        CustomPage<DriverListInfoVo> customPage = CustomPageUtils.getCustomPage(pageInfo);
        return customPage;
    }

    @Override
    public DriverListInfoVo getDriverInfoByUserId(String userId) throws ParseException {
        DriverListInfoVo Vo = hktsRealNameAuthenticationMapper.getDriverInfoByUserId(userId);
        QueryWrapper<HktsDriverDetail> query = new QueryWrapper<HktsDriverDetail>();
        query.lambda().eq(HktsDriverDetail::getDriverId,userId);
        HktsDriverDetail hktsDriverDetail = hktsDriverDetailMapper.selectOne(query);
        if(hktsDriverDetail!=null){
            NumberFormat percent = NumberFormat.getPercentInstance();
            percent.setMaximumFractionDigits(2);
            Vo.setOrderNum(hktsDriverDetail.getTradeCount());
            Vo.setFavorableRate(hktsDriverDetail.getApplauseRate() == null ? "" : percent.format(hktsDriverDetail.getApplauseRate()));
        }
        Vo.setApproval(getDayNum(Vo.getApproval(),Vo.getApprovalTime()));


        return Vo;
    }
    @Override
    public Result<Object> getDriverInfoByUserMobile(String mobile) throws ParseException {
        HktsDriver hktsDriver = driverMapper.getDriverByUserNameOrMobile(mobile);
        if (hktsDriver == null){
            return ResultUtil.error("您输入的手机号不正确或暂无该用户！");
        }
        DriverListInfoVo Vo = hktsRealNameAuthenticationMapper.getDriverInfoByUserId(hktsDriver.getId());
        QueryWrapper<HktsDriverDetail> query = new QueryWrapper<HktsDriverDetail>();
        query.lambda().eq(HktsDriverDetail::getDriverId,hktsDriver.getId());
        HktsDriverDetail hktsDriverDetail = hktsDriverDetailMapper.selectOne(query);
        if(hktsDriverDetail!=null){
            NumberFormat percent = NumberFormat.getPercentInstance();
            percent.setMaximumFractionDigits(2);
            Vo.setOrderNum(hktsDriverDetail.getTradeCount());
            Vo.setFavorableRate(hktsDriverDetail.getApplauseRate() == null ? "" : percent.format(hktsDriverDetail.getApplauseRate()));
        }
        Vo.setApproval(getDayNum(Vo.getApproval(),Vo.getApprovalTime()));
        return ResultUtil.data(Vo);
    }

    @Override
    public Result<List<DriverListInfoVo>> getDriverInfosByUserMobile(String mobile) throws ParseException {
        List<HktsDriver> hktsDrivers = driverMapper.getDriversByUserNameOrMobile(mobile);
        if (hktsDrivers == null||hktsDrivers.size()==0){
            ResultUtil.error("您输入的手机号不正确或暂无该用户！");
        }
        List<DriverListInfoVo> driverListInfoVos=new ArrayList<>();
        for (HktsDriver item:hktsDrivers){
            DriverListInfoVo Vo = hktsRealNameAuthenticationMapper.getDriverInfoByUserId(item.getId());
            Vo.setApproval(getDayNum(Vo.getApproval(),Vo.getApprovalTime()));
            driverListInfoVos.add(Vo);
        }
        return ResultUtil.data(driverListInfoVos);
    }

    /** 功能描述:
     *根据司机姓名查询司机id
     * @return: java.lang.String
     * @Author: 杨春科
     * @Date: 2021-07-29 22:08
     * @Description //TODO
     */
    @Override
    public List<String> getIdsByDriverName(String driverName) {
        QueryWrapper<HktsRealNameAuthentication> query=new QueryWrapper<HktsRealNameAuthentication>();
        query.lambda().like(HktsRealNameAuthentication::getDriverName,driverName);
        List<HktsRealNameAuthentication> hktsRealNameAuthentications = hktsRealNameAuthenticationMapper.selectList(query);
        List<String> collect = hktsRealNameAuthentications.stream().map(HktsRealNameAuthentication::getUserId).collect(Collectors.toList());
        return collect;
    }

    @Override
    public Map<String, String> getDriverNamesByIds(String ids) {
        String[] split = ids.split(",");
        QueryWrapper<HktsRealNameAuthentication> query=new QueryWrapper<HktsRealNameAuthentication>();
        query.lambda().in(HktsRealNameAuthentication::getUserId,split);
        List<HktsRealNameAuthentication> hktsRealNameAuthentications = hktsRealNameAuthenticationMapper.selectList(query);
        Map<String, String> collect = hktsRealNameAuthentications.stream().collect(Collectors.toMap(HktsRealNameAuthentication::getUserId, HktsRealNameAuthentication::getDriverName));
        return collect;
    }

    public String getDayNum(String approval, Date time ) throws ParseException {
        switch (approval)
        {
            case "1":
                approval="未认证";
                break;
            case "2":
                    approval="已认证";
                break;
            case "3":
            approval="已提交待认证";
            break;
            case "4":
                approval="认证失败";
                break;
            default:
                approval="未认证";
        }
        if(approval.equals("已认证")&&time!=null){
            int i = daysBetween(time);
            approval=approval+"  "+ i+"天";
        }
       return  approval;
    }

    public  int daysBetween(Date smdate) throws ParseException
    {
          Date bdate=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        smdate=sdf.parse(sdf.format(smdate));
        bdate=sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);

        return Integer.parseInt(String.valueOf(between_days));
    }
}
